﻿using OnWork.DataCenter.BLL.Standard;

namespace OnWork.DataCenter.Shared.Pages.DataStandard.Designer
{
    /// <summary>
    /// 保存对象
    /// </summary>
    public class StandardDesignerSaveDto
    {
        public List<NodeDto> Nodes { get; set; } = new List<NodeDto>();
        public List<LinkDto> Links { get; set; } = new List<LinkDto>();

        /// <summary>
        /// 返回结果VO
        /// </summary>
        public List<DataStandardTreeDto> ToTreeVO()
        {
            List<DataStandardTreeDto> data = new List<DataStandardTreeDto>();

            ////当出现没有连线的情况时 直接添加
            //if (Links.Count == 0)
            //{
            //    //遍历所有 节点
            //    foreach (var node in Nodes)
            //    {
            //        data.Add(new DataStandardTreeDto() { ID = node.ID, Name = node.Name });
            //    }
            //    return data;
            //}

            //获取起始节点

            var ss = Links.Select(x => x.SourceNodeId.ToString()).Distinct().ToList(); //获取源节点ID
            var ts = Links.Select(x => x.TargetNodeId.ToString()).Distinct().ToList(); //获取目标节点ID

            var all = new List<string>();
            all.AddRange(ss);
            all.AddRange(ts);

            //全部节点中不包含目标的为起始节点 可能会有多个
            var startNodeids = all.Where(x => !ts.Contains(x)).Distinct().ToList();
            //如果两边都没有连 也在起始点中
            foreach (NodeDto item in Nodes)
            {
                int linkCount = 0;
                foreach (var port in item.Ports)
                {
                    if (port.Links != null)
                    {
                        linkCount += port.Links.Count;
                    }
                }
                if (linkCount == 0)
                {
                    startNodeids.Add(item.Id);
                }
            }

            //按照垂直顺序查询
            var startNodes = Nodes.Where(x => startNodeids.Contains(x.Id)).OrderBy(x => x.Position.Y).ThenBy(x => x.Position.X).ToList();

            //遍历所有 节点
            foreach (var node in startNodes)
            {
                //var node = Nodes.Where(x => x.Id == sn).First();
                data.Add(new DataStandardTreeDto() { ID = node.ID, Name = node.Name, Childs = ToTreeGetChildrens(node.Id) });
            }

            return data;
        }

        private List<DataStandardTreeDto> ToTreeGetChildrens(string nodeId)
        {
            var childids = Links.Where(x => x.SourceNodeId.ToString() == nodeId).Select(x => x.TargetNodeId.ToString()).ToList();
            List<DataStandardTreeDto> data = new List<DataStandardTreeDto>();
            foreach (var item in childids)
            {
                var node = Nodes.Where(x => x.Id == item).First();
                data.Add(new DataStandardTreeDto() { ID = node.ID, Name = node.Name, Childs = ToTreeGetChildrens(item) });
            }
            return data;
        }
    }
}